Ext.namespace("Task.Add");

Task.Add.win = function() {
	this.users = [];
	this.usersForCc = [];
	this.origin = '1'; //来源
	this.userType=0;//1:执行人 2:抄送人
	this.userSelector = null;
	this.userSelectorForCc = null;
	this.ccUserSelector = [];
	this.selectUserId = [];
	this.loadMask = null;
	this.taskId;
	this.isTd;
	this.successUrl;
	this.failUrl;
	this.saveOrUpdate;
	this.hasAccessory;
	
	this.txtTitle = new Ext.form.TextField({
        fieldLabel: '任务名称',
        width: 250,
        allowBlank: false,
        blankText: '请输入任务名称!',
        maxLength:50
    });
	this.txtExecutor = new Ext.form.TextField({
		fieldLabel: '执行人',
		readOnly: false,
		width: 250,
		allowBlank: false,
		blankText: '请选择执行人',
		listeners: {
			   'render': function(cmp) {
					var self = cmp.ownerCt.ownerCt;
					var self = cmp.ownerCt.ownerCt.ownerCt.ownerCt.ownerCt;
					cmp.getEl().on('click', function(){ self.showUser1();}, self); 
				}
			}
	});
	this.txtTaskCC = new Ext.form.TextField({
		fieldLabel: '抄送人',
		readOnly: true,
		width: 200,
		blankText: '抄送人',
		listeners: {
			   'render': function(cmp) {
					//var self = cmp.ownerCt.ownerCt;
					var self = cmp.ownerCt.ownerCt.ownerCt.ownerCt.ownerCt;
					cmp.getEl().on('click', function(){ self.showUser2();}, self); 
				}
			}
	});
	this.txtTaskOrigin = new Ext.form.ComboBox({
		width: 100,
		fieldLabel: '任务来源',
        store: new Ext.data.ArrayStore({
        	fields: ['value', 'name'],
        	data: OMS.TASKORIGINVALUE
        }),
        value: '11',
        valueField: 'value',
        displayField: 'name',
        editable: false,
        allowBlank: false,
        mode: 'local',
        triggerAction: 'all',
        selectOnFocus: true
	});
	
	this.txtContent = new Ext.form.HtmlEditor({
		fieldLabel: '任务内容',
		width:475,
		height:100,
		enableSourceEdit: false,
		allowBlank: false,
		autoScroll:true
	});
	this.dtFeedback = new Ext.ux.form.DateTime({
		fieldLabel: '完成时限',
		timeFormat:'H:i',
        timeConfig: {
             altFormats:'H:i',
            allowBlank: true    
        },
        dateFormat:'Y-m-d',
        dateConfig: {
        	width:40,
            altFormats:'Y-m-d',
            allowBlank: false    
       }
	});
	this.chkRemind = new Ext.form.CheckboxGroup({
		width:120,
		fieldLabel: '提醒设置',
		items: [
		      {boxLabel: '短信', name: 'smsRemind',inputValue: '1'},
		      {boxLabel: '邮件', name: 'emailRemind',inputValue: '2'}
		]
	});	
	this.difficult = new Ext.form.HtmlEditor({
		width:475,
		height:100,
		enableSourceEdit: false,
		allowBlank: false,
		autoScroll:true
	});
	
	this.remark = new Ext.form.TextArea({
		fieldLabel:'任务备注',
		width:450,
		height:30,
		maxLength:200,
		hidden:true
	});
	this.taskType = new Ext.form.ComboBox({
		width: 100,
		fieldLabel: '任务类型',
        store: new Ext.data.ArrayStore({
        	fields: ['value', 'name'],
        	data: OMS.PLANCATEGORY2
        }),
        value: 1,
        valueField: 'value',
        displayField: 'name',
        mode: 'local',
        triggerAction: 'all',
        selectOnFocus: true
	});
	/*this.upfile = new Ext.form.FileUploadField({
		fieldLabel : '上传附件',
		emptyText: '请选择要上传的文件',
		width : 500,
		name : 'fileName',
		buttonText: '',
		buttonCfg: {
            iconCls: 'icon-compress'
        }
	});*/

	this.form = new Ext.FormPanel({
		title: '基本信息',
        bodyStyle: 'padding: 5px 5px 0',
        labelWidth: 55,
        frame:true,
        //fileUpload: true, 
        autoScroll: true,
        labelAlign: 'right',
        autoWidth : true,
        items : [
				{
					layout : 'column',
					defaults : {
						layout : 'form'
					},
					items : [ {
						columnWidth : .6,
						items : [ this.txtTitle]
					},{
						columnWidth : .4,
						items : [this.txtTaskOrigin]
					},{
						columnWidth : 1,
						items : [this.txtContent]
					},{
						columnWidth : 1,
						items : [this.difficult]
					},{
						columnWidth : .6,
						items : [ this.dtFeedback,this.txtExecutor]
					},{
						columnWidth : .4,
						items : [this.taskType ,  this.chkRemind]
					}/*,{
						columnWidth : .5,
						items : [ this.txtTaskCC]
					},{
						columnWidth : 1,
						items : [this.upfile]
					}*/
					]
				} ]
    });
    this.btnSave = new Ext.Button({
    	text:'保存草稿箱',
    	handler:function(){this.save("");},
    	scope: this
    });
    this.btnSend = new Ext.Button({
    	text:'保存并下发',
    	handler:function(){this.save(true);},
    	scope: this
    });
	this.addCon = new Ext.data.Connection({
		url:'../task/addTask.form?timesnap=' + Date.parse(new Date()),
		method:'post'
	});
	this.tabPanel  = new Ext.TabPanel({
		height:450,
		autoWidth : true,
		listeners:{
			tabchange:this.showButtons
		}
	});
	this.tabPanel.add(this.form);
	this.tabPanel.activate(this.form);
	//this.taskUpFile = new Task.UpFile.panel();
	this.taskUploadPanel = new Task.UpFile.panel();
	this.tabPanel.add(this.taskUploadPanel);
	Task.Add.win.superclass.constructor.call(this, {
		title: '任务派发',
        bodyStyle: 'padding: 0px 0px 0',
        
        height:400,
        width: 680,
        y: 50,
        resizable: false,
        plain: true,
        modal: true,
        closeAction: 'hide',
        items: [this.tabPanel],
        buttons: [this.btnSave,this.btnSend,{
            text: '关闭',
            scope: this,
            handler: function() {
	        	if (this.isTd) {
					window.close();
				}
	        	this.hide();
        		//this.hide.createDelegate(this, []);
        	}
        }],
        buttonAlign:'center'
	});
};
Ext.extend(Task.Add.win, Ext.Window, {
	showButtons:function(){	
	    var j = this.ownerCt;
		//if(this.getActiveTab().title=='基本信息'){
			if(j.saveOrUpdate=="detail"){
			}else{
				j.buttons[0].show();
				j.buttons[1].show();
			}
		/*}else if(this.getActiveTab().title=='附件信息'){
			j.buttons[0].hide();
			j.buttons[1].hide();	
		}*/
		
	},
	initAdd:function(){
		this.setTitle("任务新建");
		this.users=[];
		this.saveOrUpdate="save";
		this.form.getForm().reset();
		this.addCon.url='../task/addTask.form?timesnap=' + Date.parse(new Date());
		
		this.taskUploadPanel.fileForm.removeAll(true);
		this.taskUploadPanel.fileForm.getForm().reset();
		this.taskUploadPanel.initFeedBack(null);
		this.taskUploadPanel.queryUpfile(null);
		if(this.taskExecuteStatusPanel)
		this.tabPanel.remove(this.taskExecuteStatusPanel);
		if(this.TaskRemindPanel)
			this.tabPanel.remove(this.TaskRemindPanel);
		this.difficult.hide();
		this.btnSave.setText('保存草稿箱');
		this.btnSave.show();
		this.btnSend.show();
		
	},
	initTdAdd:function(ob){
		this.saveOrUpdate="save";
		this.users=[];
		this.isTd =true;
		this.form.getForm().reset();
		
		this.taskUploadPanel.fileForm.removeAll(true);
		this.taskUploadPanel.fileForm.getForm().reset();
		this.txtTitle.setValue(ob.taskTitle);
		var url = "<a href="+ob.accessUrl+">连接地址</a><br/>";
		this.txtContent.setValue(url+ ob.taskContent);
		this.txtTaskOrigin.setValue(ob.taskOrigin);
		this.addCon.url='../task/addTask.form?timesnap=' + Date.parse(new Date());
		this.btnSave.setText('保存草稿箱');
		this.btnSend.show();
		this.txtExecutor.setValue(ob.userBranchNames);
		if(ob.userBranchIds){
			this.selectUserId = ob.userBranchIds.split(',');
		}
		//this.selectUserId.push(ob.userBranchIds);
		this.successUrl = ob.successUrl;
		this.failUrl= ob.failUrl;
		
	},
	initUpdate:function(data,detail){
		this.saveOrUpdate="update";
		this.btnSend.hide();
		this.btnSave.setText('回复');
		this.txtContent.fieldLabel="寻呼回顾";
		this.setTitle("寻呼回复");
		if(detail&&detail=='detail'){
			this.setTitle("寻呼详情");
			this.saveOrUpdate="detail";
			if(!this.taskExecuteStatusPanel)
			this.taskExecuteStatusPanel = new Task.ExecuteStatus.panel();
			this.tabPanel.add(this.taskExecuteStatusPanel);
			this.taskExecuteStatusPanel.initFeedBack(data.TASK_ID);
			this.taskExecuteStatusPanel.queryUpfile(data.TASK_ID);
			if(!this.TaskRemindPanel)
				this.TaskRemindPanel = new Task.Remind.panel();
				this.tabPanel.add(this.TaskRemindPanel);
				this.TaskRemindPanel.initFeedBack(data.TASK_ID);
				this.TaskRemindPanel.queryUpfile(data.TASK_ID);			
			this.btnSave.hide();
			
		}else{
			
			if(this.taskExecuteStatusPanel)
			this.tabPanel.remove(this.taskExecuteStatusPanel);
			
			if(this.TaskRemindPanel)
				this.tabPanel.remove(this.TaskRemindPanel);
			this.btnSave.show();
		}
		this.form.getForm().reset();		
		this.taskId = data.TASK_ID;
		this.taskUploadPanel.fileForm.removeAll(true);
		this.taskUploadPanel.fileForm.getForm().reset();
		this.taskUploadPanel.initFeedBack(data.TASK_ID);
		this.taskUploadPanel.queryUpfile(data.TASK_ID);
		this.txtTitle.setValue(data.TASK_TITLE);
		
		this.txtContent.setValue(data.TASK_CONTENT);
		zhangyi
		
		this.dtFeedback.setValue(data.TASK_COMPLETE_DATE);
		this.txtTaskOrigin.setValue(data.TASK_ORIGIN);
		this.txtTaskCC.setValue(data.TASK_CCUSERNAME);
		if(data.REMIND_SET==1){
			this.chkRemind.items.items[0].setValue(true);
		}else if (data.REMIND_SET==2){
			this.chkRemind.items.items[1].setValue(true);
		}else if(data.REMIND_SET==3){
			this.chkRemind.items.items[0].setValue(true);
			this.chkRemind.items.items[1].setValue(true);
		}
		this.difficult.setValue(data.TASK_DIFFICULTY);
		this.remark.setValue(data.TASK_REMARK);
		this.taskType.setValue(data.TASK_TYPE);
		this.addCon.url='../task/uptTask.form?timesnap=' + Date.parse(new Date());
		this.btnSend.hide();
		this.hasAccessory=data.HAS_ACCESSORY;
		var conn = new Ext.data.Connection({
			url:'../task/searchTaskExes.form?timesnap=' + Date.parse(new Date()),
			method:'post'
		});
		Utils.request(conn,{
			params:{
				taskId:this.taskId
			},
			scope:this,
			success:function(data){
				//if (!this.scope.userSelector) {
				//	this.scope.userSelector = new Selector.User(this.scope, '执行人');
				//}
				this.scope.userSelector=null;
				var userNames = [];
				var userData =[];
				var userId = [];
				this.scope.users =[];
				this.scope.selectUserId =[];
				
				for(var i =0;i<data.exes.length;i++){
					userNames.push(data.exes[i].USER_NAME);
					userId.push(data.exes[i].USER_ID);
					this.scope.selectUserId.push(data.exes[i].USER_ID);
					
					//var o ={};
					//o.id=data.exes[i].USER_ID;
					//o.name = data.exes[i].USER_NAME;
					//this.scope.users.push(o);
				}
				this.scope.txtExecutor.setValue(userNames.join(';'));
			}
		});
	},
/*	stripTags:function(str)   {  
        return   str.replace(/<\/?[^>]+>/gi,   '');  
    },*/
	save: function(send) {
/*    	var htmlEV = this.stripTags(this.txtContent.getValue());
    	
		//alert(htmlEV.length);
    	alert(this.txtContent.getValue());
		alert(this.txtContent.getValue().length);
		*/
		if(this.txtContent.getValue().length>20000){
			Utils.info("任务内容不能超过10000个字","系统提示");
			return;
		}
		if(!this.form.getForm().isValid()){
			Utils.info("有必填项没有填写，请检查！","系统提示");
			return;
		}
		if(this.selectUserId.length==0){
			//Utils.info('请选择执行人！');
			//return;
		}

		if (!this.loadMask) {
			 this.loadMask = new Ext.LoadMask(this.form.getEl(), {msg: '派发中，请稍候...'});
		}

		var date = this.dtFeedback.getValue();
		var flag = send!='' ? 'send' : '';
		var task_status = send!='' ? '1' : '0';
		var iptvalue =null;
		if(this.chkRemind.items.items[0].checked){
			iptvalue=1;
		}
		if(this.chkRemind.items.items[1].checked){
			iptvalue=2;
		}
		if(this.chkRemind.items.items[0].checked&this.chkRemind.items.items[1].checked){
			iptvalue=3;
		}
		scope=this;
		var urlstr; 
		//url:'../task/addTaskFile.form?timesnap=' +new Date().getTime(),
		if(this.saveOrUpdate=="save"){
			urlstr='../task/addTask.form?timesnap=' +new Date().getTime();
		}else{
			urlstr='../task/uptTask.form?timesnap=' +new Date().getTime();
		}
		/*if(this.upfile.getValue()!= null & this.upfile.getValue() != ''){
			this.hasAccessory=0;
		}else{

		}*/
		//this.txtContent.syncValue();
		var params={
				taskId:this.taskId,
				title:this.txtTitle.getValue(),
				content:this.txtContent.getValue(),
				origin:this.txtTaskOrigin.getValue(),
				complete_date: date.format('Y-m-d H:i:s'),
				flag : flag,
				task_status : task_status,
				executor:this.selectUserId.join(','),
				taskCcUser : this.ccUserSelector.join(','),//(!this.ccUserSelector) ? '' : this.ccUserSelector.join(','),
				executorNames:this.txtExecutor.getValue(),
				taskCcUserNames:this.txtTaskCC.getValue(),
				chkRemind:iptvalue,
				difficulty:this.difficult.getValue(),
				remark:this.remark.getValue(),
				taskType:this.taskType.getValue(),
				//fileName:this.upfile.getValue(),
				has_accessory:this.hasAccessory,
				fileRemark:'派发附件'
			};
		//alert(Ext.util.JSON.encode(params));
		//alert(this.taskUploadPanel.fileForm.getForm());
		this.tabPanel.activate(this.taskUploadPanel);
		//this.form.getForm().submit({
		this.taskUploadPanel.fileForm.getForm().submit({
			waitTitle : '系统提示',
			waitMsg : '数据提交中，请稍候...',
			url:urlstr,
			method:'post',
		//Utils.request(this.addCon,{
			params:params,			
			flag:flag,
			success:function(){
				Utils.info("操作成功","系统提示");
				scope.hide();
				if(scope.isTd){
					if (!this.scope.successUrl) return;
					window.location.href=scope.successUrl;
				}else{
					if(flag=='send'){
						Task.Sended.panel.instance.store.reload();
					}else{
						Task.Assign.panel.instance.store.reload();
					}
				}
			},
			failure:function(){
				if(scope.isTd){
					if (!scope.failUrl) return;
					window.location.href=scope.failUrl;
				}
			}
		});
	},
	showUser1:function(){
		var scope=this;
		//this.selectUserId = [129]; 
		//console.info(this.selectUserId);
		if(this.userSelector==null){
			this.userSelector=new Tree.User(this.selectUserId,function(o){
				scope.setUsers1(o);
			},null,'101');
		}
		this.userSelector.show();
	},
	showUser2:function(){
		var scope=this;
		//this.ccUserSelector = [7190,3840,20153];
		if(this.userSelectorForCc==null){
			this.userSelectorForCc=new Tree.User(this.ccUserSelector,function(o){
				scope.setUsers2(o);
			},null,'101');
		}
		this.userSelectorForCc.show();
	},
	setUsers1:function(o){
		//console.info(Ext.util.JSON.encode(o));
		//alert(Ext.util.JSON.encode(o));
		var names = [];
		this.selectUserId =[];
		for(var i=0;i<o.length;i++) {
			names.push(o[i].text);
			this.selectUserId.push(o[i].id);
		}
		this.txtExecutor.setValue(names.join(';'));
	},
	setUsers2:function(o){
		var names = [];
		this.ccUserSelector =[];
		for(var i=0;i<o.length;i++) {
			names.push(o[i].text);
			this.ccUserSelector.push(o[i].id);
		}	
		this.txtTaskCC.setValue(names.join(';'));
	}
});

